package com.china_goldcard.loadingbutton;

import java.util.Timer;
import java.util.TimerTask;

public class ProgressGenerator {

    private Timer timer;
    private int mProgress;
    private int interval = 5;

    /**
     * 构造函数
     * @param interval
     */
    public ProgressGenerator(int interval){
         this.interval = interval;
    }

    /**
     * 开始
     * @param button
     */
    public void start(final ProcessButton button) {
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                mProgress += interval;
                if (mProgress >= 100) {
                    mProgress = interval;
                }
                button.post(new Runnable() {
                    @Override
                    public void run() {
                        button.setProgress(mProgress);
                    }
                });
            }
        };
        button.setEnabled(false);
        button.setProgress(0);
        timer = new Timer();
        timer.schedule(timerTask,0,1000);
    }

    /**
     * 结束
     * @param button
     */
    public void stop(final ProcessButton button, final boolean succ){
        timer.cancel();
        timer = null;
        button.post(new Runnable() {
            @Override
            public void run() {
                button.setProgress(succ ? 100 : -1);
                button.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        button.setProgress(0);
                        button.setEnabled(true);
                        mProgress = 0;
                    }
                },2000);
            }
        });
    }
}
